package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    RestHighLevelClient client;


    @Autowired
    ApUserSearchService userSearchService;
    /**
     * ES文章分页搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto){
        //参数校验
        if(dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //异步调用记录搜索关键字
        ApUser user = AppThreadLocalUtils.getUser();
        if(user!=null){
//            //如果当前用户登录的话才记录用户搜索关键字
            dto.setUserID(user.getId());
            userSearchService.insert(dto);
        }


        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag("__all__");
        }
        // 1.创建SearchSourceBuilder对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //  1.1.添加查询条件QueryBuilders
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
       //按照标题查询  标题一定不为空
        // 2.构建matchQuery对象,查询信息为      title   <====>   标题
        MatchQueryBuilder title = QueryBuilders.matchQuery("title", dto.getSearchWords());
        //前端查询页面包含了一个tag数据,但是索引库创建字段时没有这个数据
        boolQueryBuilder.must(title);
        if (!dto.getTag().equals("__all__")){
            MatchQueryBuilder tag = QueryBuilders.matchQuery("tag", dto.getTag());
            boolQueryBuilder.must(tag);
        }
        //***********************************************查询小于最小时间的数据,用来做分页***********************************************
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        //根据时间倒叙进行范围查询
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //设置分页参数
        if (dto.getPageSize()>10){
            dto.setPageSize(10);
        }
        //from   为什么是0
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());

        //指定查询索引库的名称
        SearchRequest request = new SearchRequest("app_info_article");

        try {
            //高亮设置在提交请求之前
            HighlightBuilder highlight = SearchSourceBuilder.highlight();
            highlight.field("title");  // 高亮显示域
            highlight.preTags("<font style='color:red'>"); // 高亮显示前缀
            highlight.postTags("</font>");  // 高亮显示后缀
            sourceBuilder.highlighter(highlight);
            sourceBuilder.query(boolQueryBuilder);
            // 3.添加SearchSourceBuilder对象到SearchRequest对象中
            request.source(sourceBuilder);
            // 4.发起请求，得到结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            //高亮数据设置
            List<Map> resultList = new ArrayList<>();
            //遍历数据来插入
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                Map article = JSON.parseObject(sourceAsString, Map.class);
                //设置高亮显示区域
                HighlightField highlightField = hit.getHighlightFields().get("title");
                if (StringUtils.isNotBlank(highlightField.toString())) {
                    Text[] fragments = highlightField.fragments();
//                    article.put("o_title", article.get("title"));
                    String join = StringUtils.join(fragments);
                    article.put("title",join);
                }
                resultList.add(article);
            }
            return ResponseResult.okResult(resultList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到相关的数据");
    }
}